// ==UserScript==
// @name        Userstyles.org一键安装
// @namespace   blog.sylingd.com
// @match       https://userstyles.org/styles/browse*
// @version     1
// @updateURL   https://git.oschina.net/sy/shuangya/raw/master/userjs/Userstyles_one_key.user.js
// @downloadURL https://git.oschina.net/sy/shuangya/raw/master/userjs/Userstyles_one_key.user.js
// ==/UserScript==

(function() {
	'use strict';
	var install_button_click = function(e) {
		var title = this.parentElement.parentElement.querySelector('.ellipsis a');
		var id = title.href.match(/styles\/(\d+)\//)[1];
		var name = title.innerHTML;
		document.querySelector('link[rel="xstyle-name"]').setAttribute('href', name);
		document.querySelector('link[rel="xstyle-code"]').setAttribute('href', 'https://userstyles.org/styles/chrome/' + id + '.json');
		var newEvent = new CustomEvent('xstyleInstall', {detail: null});
		document.dispatchEvent(newEvent);
	};
	var waitingForRender = function(callback) {
		var _t = setTimeout(function() {
			clearTimeout(_t);
			_t = null;
			if (document.getElementById('centralMsg') === null && document.querySelector(".style_card") === null) {
				waitingForRender(callback);
			} else {
				callback();
			}
		}, 400);
	};
	// insert some element
	if (document.querySelector('link[rel="xstyle-code"]') === null) {
		var code_link = document.createElement('link');
		code_link.setAttribute('rel', 'xstyle-code');
		document.head.appendChild(code_link);
		var name_link = document.createElement('link');
		name_link.setAttribute('rel', 'xstyle-name');
		document.head.appendChild(name_link);
	}
	waitingForRender(function() {
		Array.prototype.forEach.call(document.querySelectorAll(".style_card"), function(el) {
			var installEl = el.querySelector('.tooltip');
			installEl.style.cursor = "pointer";
			installEl.title = "点击安装";
			installEl.addEventListener('click', install_button_click);
		});
	});
})();